﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using tracker.Models.BLL;
using tracker.Models;
using System.Data;
using tracker.Models.DTO;

namespace tracker.Controllers
{
    public class HandlerSearchHistoryController : Controller
    {
       /// <summary>
       /// Get All Alarm Define
       /// </summary>
       /// <returns></returns>
        [CallAjaxFilter]
        public JsonStringResult Index(string fromtime, string totime, string limit, string start, string speedCompare, string speedNumber, string trackName, string filterData)
        {

            string result = "";
            string _username = HttpContext.Session[Common.USER].ToString();
            string _language = HttpContext.Session[Common.LANGUAGE].ToString();
            string timezone = HttpContext.Session[Common.TIMEZONE].ToString();
            _language = _language == string.Empty ? "vi" : _language;

            

            if (fromtime == null || totime == null || limit == null || start == null || trackName == null)
            {
                result = "{totalCount:0,data:[{}]}";
            }
            else
            {
                if (ClassCommon.classValidate.isDateTime(fromtime) && ClassCommon.classValidate.isDateTime(totime) && ClassCommon.classValidate.isInt(limit) && ClassCommon.classValidate.isInt(start) && ClassCommon.classValidate.isInt(speedNumber))
                {
                    List<ETrackLog> listTrackLog = new List<ETrackLog>();
                    List<ENTTrackerName> listTrackerName = new List<ENTTrackerName>();
                    listTrackerName = HandlerSearchTrackerNameController.getListDeviceByUser(_username);

                    if (filterData == null)
                    {
                        #region Filter Data NULL
                        if (listTrackerName.Count > 0)
                        {
                            string username = "";
                            foreach (ENTTrackerName item in listTrackerName)
                            {
                                username += item.username + ",";
                            }
                            username = username.Remove(username.LastIndexOf(","));

                            if (speedCompare == ">=")
                                listTrackLog = TrackLogBLL.GetRecodeBySearchSpeedAlarmMoreThan(new string[]{"SpeedNumber",
                                                                                                            "TrackName",
                                                                                                            "Start",
                                                                                                            "End",
                                                                                                            "FromTime",
                                                                                                            "ToTime",
                                                                                                            "UserName"
                                                                                                },
                                                                                               new object[]{float.Parse(speedNumber),
                                                                                                            trackName,
                                                                                                            start, 
                                                                                                            start + limit  , 
                                                                                                            ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                                            ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                                            username
                                                                                               }); 

                            else
                                listTrackLog = TrackLogBLL.GetRecodeBySearchSpeedAlarmLessThan(new string[]{"SpeedNumber",
                                                                                                            "TrackName",
                                                                                                            "Start",
                                                                                                            "End",
                                                                                                            "FromTime",
                                                                                                            "ToTime",
                                                                                                            "UserName"
                                                                                                },
                                                                                               new object[]{float.Parse(speedNumber),
                                                                                                            trackName,
                                                                                                            start, 
                                                                                                            start + limit  , 
                                                                                                            ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                                            ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                                            username
                                                                                               }); 

                            if (listTrackLog.Count > 0)
                            {
                                List<ELastDeviceInfo> listDeviceInfo = new List<ELastDeviceInfo>();

                                foreach (ETrackLog item in listTrackLog)
                                {
                                    ELastDeviceInfo entLastDeviceInfo = new ELastDeviceInfo();
                                    //Alarm Code

                                    entLastDeviceInfo.alarminfo = item.AlarmCode;
                                    entLastDeviceInfo.alarmlatitude = item.Latitude;
                                    entLastDeviceInfo.alarmlongitude = item.Longitude;
                                    entLastDeviceInfo.lastalarmtime = ClassCommon.gpsExtensionMethod.convertGMTClientTime(DateTime.Parse(item.RecieveTime.ToString()), timezone).ToString("yyyy-MM-dd hh:mm:ss tt");
                                    entLastDeviceInfo.alarmspeed = item.Speed;


                                    entLastDeviceInfo.altitude = item.Altitude;
                                    entLastDeviceInfo.devicename = item.DeviceName;
                                    entLastDeviceInfo.direction = item.Direction;

                                    entLastDeviceInfo.devicestate = "0";
                                    // entLastDeviceInfo.geofenceid = 100;
                                    entLastDeviceInfo.lastgeofencename = "";
                                    entLastDeviceInfo.hasgsmlocation = "";
                                    entLastDeviceInfo.RFID = "";
                                    entLastDeviceInfo.status = item.Gps_status.ToLower() == "valid" ? "true" : "false"; ;
                                    entLastDeviceInfo.gpsavailable = item.Gps_status.ToLower() == "valid" ? true : false;

                                    entLastDeviceInfo.runtime = item.RunTime;
                                    entLastDeviceInfo.satellites = item.Satellites;
                                    entLastDeviceInfo.gsmsignal = item.Gsm_Signal;
                                    entLastDeviceInfo.gpstime = ClassCommon.gpsExtensionMethod.convertGMTClientTime(DateTime.Parse(item.Gps_time.ToString()), timezone).ToString("yyyy-MM-dd hh:mm:ss tt");
                                    entLastDeviceInfo.HDOP = item.Hdop;
                                    entLastDeviceInfo.journey = item.Journey;
                                    entLastDeviceInfo.latitude = item.Latitude;
                                    entLastDeviceInfo.longitude = item.Longitude;
                                    entLastDeviceInfo.online = item.Gps_status;
                                    entLastDeviceInfo.receivedtime = ClassCommon.gpsExtensionMethod.convertGMTClientTime(DateTime.Parse(item.RecieveTime.ToString()), timezone).ToString("yyyy-MM-dd hh:mm:ss tt");
                                    entLastDeviceInfo.speed = item.Speed;
                                    entLastDeviceInfo.sssid = item.DeviceKeySecurity;

                                    listDeviceInfo.Add(entLastDeviceInfo);
                                }
                                int iCount = 0;
                                DataTable dtData = new DataTable();
                                if (speedCompare == ">=")
                                    dtData = TrackLogBLL.GetTotalRecordBySearchSpeedAlarmMoreThan(new string[]{"SpeedNumber",
                                                                                                                "TrackName",
                                                                                                                "Start",
                                                                                                                "End",
                                                                                                                "FromTime",
                                                                                                                "ToTime",
                                                                                                                "UserName"
                                                                                                    },
                                                                                                   new object[]{float.Parse(speedNumber),
                                                                                                                trackName,
                                                                                                                0, 
                                                                                                                60000, 
                                                                                                                ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                                                ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                                                username
                                                                                                   }).Tables[0]; 

                                else
                                    dtData = TrackLogBLL.GetTotalRecordBySearchSpeedAlarmLessThan(new string[]{"SpeedNumber",
                                                                                                                        "TrackName",
                                                                                                                        "Start",
                                                                                                                        "End",
                                                                                                                        "FromTime",
                                                                                                                        "ToTime",
                                                                                                                        "UserName"
                                                                                                            },
                                                                                                       new object[]{float.Parse(speedNumber),
                                                                                                                        trackName,
                                                                                                                        0, 
                                                                                                                        60000, 
                                                                                                                        ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                                                        ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                                                        username
                                                                                                           }).Tables[0];
                                if (dtData.Rows.Count > 0)
                                    iCount = int.Parse(dtData.Rows[0]["Total"].ToString());

                                if (listDeviceInfo.Count > 0)
                                {
                                    result = Utilities.getJsonString(listDeviceInfo, "totalCount:" + iCount.ToString() + ",data:", 1);
                                }
                                else
                                {
                                    result = "{totalCount:0,data:[]}";
                                }
                            }
                            else
                            {
                                result = "{totalCount:0,data:[]}";
                            }
                        }
                        else
                        {
                            result = "{totalCount:0,data:[]}";
                        }
                        #endregion
                    }
                    else
                    {
                        #region Filter Data Not NULL
                        if (listTrackerName.Count > 0)
                        {
                            string username = "";
                            foreach (ENTTrackerName item in listTrackerName)
                            {
                                username += item.username + ",";
                            }
                            username = username.Remove(username.LastIndexOf(","));

                            if (speedCompare == ">=")
                                listTrackLog = TrackLogBLL.GetRecodeBySearchSpeedAlarmMoreThanLineChart(trackName,
                                                                                                        new string[]{"SpeedNumber",
                                                                                                                     "TrackName",
                                                                                                                     "Start",
                                                                                                                     "End",
                                                                                                                     "FromTime",
                                                                                                                     "ToTime",
                                                                                                                     "UserName"
                                                                                                        },
                                                                                                        new object[]{float.Parse(speedNumber),
                                                                                                                     trackName,
                                                                                                                     int.Parse(start),
                                                                                                                     int.Parse(start + limit ),
                                                                                                                     ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                                                     ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                                                     username
                                                                                                        });
                            else
                                listTrackLog = TrackLogBLL.GetRecodeBySearchSpeedAlarmLessThanLineChart(trackName,
                                                                                                        new string[]{"SpeedNumber",
                                                                                                                     "TrackName",
                                                                                                                     "Start",
                                                                                                                     "End",
                                                                                                                     "FromTime",
                                                                                                                     "ToTime",
                                                                                                                     "UserName"
                                                                                                            },
                                                                                                        new object[]{float.Parse(speedNumber),
                                                                                                                     trackName,
                                                                                                                     int.Parse(start),
                                                                                                                     int.Parse(start + limit ),
                                                                                                                     ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                                                     ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                                                     username
                                                                                                            });

                            if (listTrackLog.Count > 0)
                            {
                                List<ELastDeviceInfo> listDeviceInfo = new List<ELastDeviceInfo>();

                                foreach (ETrackLog item in listTrackLog)
                                {
                                    ELastDeviceInfo entLastDeviceInfo = new ELastDeviceInfo();
                                    //Alarm Code
                                    entLastDeviceInfo.gpstime = ClassCommon.gpsExtensionMethod.convertGMTClientTime(DateTime.Parse(item.Gps_time.ToString()), timezone).ToString("yyyy-MM-dd hh:mm:ss tt");
                                    entLastDeviceInfo.speed = item.Speed;

                                    listDeviceInfo.Add(entLastDeviceInfo);
                                }
                                int iCount = 0;
                                DataTable dtData = new DataTable();
                                if (speedCompare == ">=")
                                    dtData = TrackLogBLL.GetTotalRecordBySearchSpeedAlarmMoreThanLineChart(new string[]{"SpeedNumber",
                                                                                                                       "TrackName",
                                                                                                                       "Start",
                                                                                                                       "End",
                                                                                                                       "FromTime",
                                                                                                                       "ToTime",
                                                                                                                       "UserName"
                                                                                                              },
                                                                                                              new object[]{float.Parse(speedNumber),
                                                                                                                       trackName,
                                                                                                                       int.Parse(start),
                                                                                                                       int.Parse(start + limit ),
                                                                                                                       ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                                                       ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                                                       username
                                                                                                              }).Tables[0];
                                else
                                    dtData = TrackLogBLL.GetTotalRecordBySearchSpeedAlarmLessThanLineChart(new string[]{"SpeedNumber",
                                                                                                                       "TrackName",
                                                                                                                       "Start",
                                                                                                                       "End",
                                                                                                                       "FromTime",
                                                                                                                       "ToTime",
                                                                                                                       "UserName"
                                                                                                              },
                                                                                                              new object[]{float.Parse(speedNumber),
                                                                                                                       trackName,
                                                                                                                       int.Parse(start),
                                                                                                                       int.Parse(start + limit ),
                                                                                                                       ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                                                       ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                                                       username
                                                                                                              }).Tables[0];
                                if (dtData.Rows.Count > 0)
                                    iCount = int.Parse(dtData.Rows[0]["Total"].ToString());

                                if (listDeviceInfo.Count > 0)
                                {
                                    result = Utilities.getJsonString(listDeviceInfo, "totalCount:" + iCount.ToString() + ",data:", 1);
                                }
                                else
                                {
                                    result = "{totalCount:0,data:[]}";
                                }

                            }
                            else
                            {
                                result = "{totalCount:0,data:[]}";
                            }
                        }
                        else
                        {
                            result = "{totalCount:0,data:[]}";
                        }
                        #endregion
                    }
                }
                else
                {
                    result = "{totalCount:0,data:[]}";
                }
            }
            return new JsonStringResult(result);
        }
    }
}
